// 成就系统API
import { NextRequest } from 'next/server';
import { AchievementDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取用户成就
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 开发模式：检查表是否存在，不存在返回Mock数据
    if (process.env.NODE_ENV === 'development') {
      try {
        await AchievementDB.getAllAchievements();
      } catch (error) {
        // 表不存在，返回Mock数据
        console.log('⚠️ 成就表不存在，返回Mock数据');
        return ApiResponse.success({
          achievements: [
            { id: 1, achievement_key: 'first_answer', name: '初次尝试', description: '完成第一道题目', icon: '🌱', category: 'practice', points: 5, rarity: 'common', unlocked: false, unlockedAt: null },
            { id: 2, achievement_key: 'beginner', name: '入门学习者', description: '完成10道题目', icon: '📚', category: 'practice', points: 10, rarity: 'common', unlocked: false, unlockedAt: null },
          ],
          categories: {
            practice: [
              { id: 1, achievement_key: 'first_answer', name: '初次尝试', description: '完成第一道题目', icon: '🌱', category: 'practice', points: 5, rarity: 'common', unlocked: false, unlockedAt: null },
            ],
            accuracy: [],
            streak: [],
            speed: [],
          },
          stats: {
            total_achievements: 0,
            total_points: 0,
            legendary_count: 0,
            epic_count: 0,
            rare_count: 0,
            common_count: 0,
          },
        });
      }
    }

    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const checkNew = searchParams.get('checkNew') === 'true';

    if (checkNew) {
      // 检查并解锁新成就
      const newAchievements = await AchievementDB.checkAndUnlock(currentUser.userId);
      
      return ApiResponse.success({
        newAchievements,
        hasNew: newAchievements.length > 0,
      });
    }

    // 获取所有成就定义
    const allAchievements = await AchievementDB.getAllAchievements();
    
    // 获取用户已解锁的成就
    const userAchievements = await AchievementDB.getUserAchievements(currentUser.userId);
    
    // 获取用户成就统计
    const stats = await AchievementDB.getUserAchievementStats(currentUser.userId);

    // 标记已解锁的成就
    const unlockedIds = new Set(userAchievements.map((a: any) => a.achievement_id));
    const achievementsWithStatus = allAchievements.map((achievement: any) => ({
      ...achievement,
      unlocked: unlockedIds.has(achievement.id),
      unlockedAt: userAchievements.find((a: any) => a.achievement_id === achievement.id)?.unlocked_at || null,
    }));

    // 按分类分组
    const categories = {
      practice: achievementsWithStatus.filter((a: any) => a.category === 'practice'),
      accuracy: achievementsWithStatus.filter((a: any) => a.category === 'accuracy'),
      streak: achievementsWithStatus.filter((a: any) => a.category === 'streak'),
      speed: achievementsWithStatus.filter((a: any) => a.category === 'speed'),
    };

    return ApiResponse.success({
      achievements: achievementsWithStatus,
      categories,
      stats: stats || {
        total_achievements: 0,
        total_points: 0,
        legendary_count: 0,
        epic_count: 0,
        rare_count: 0,
        common_count: 0,
      },
    });
  } catch (error) {
    console.error('获取成就错误:', error);
    return ApiResponse.serverError('获取成就失败');
  }
}

